#include "stdafx.h"
#include "Wtalk.h"
#include "ChatFrameMgr.h"
#include "ChatFrame.h"
#include "IMLogic.h"
#include "AccountInfoMgr.h"

CChatFrameMgr *CChatFrameMgr::s_Instance = NULL;

CChatFrameMgr::CChatFrameMgr(void)
:m_pLogic(NULL)
{
	Init();
}

CChatFrameMgr::~CChatFrameMgr(void)
{
	DestroyAllChatFrame();
}

CChatFrameMgr *CChatFrameMgr::GetInstance()
{
	if (!s_Instance)
	{
		s_Instance = new CChatFrameMgr;
		_ASSERTE(s_Instance);
	}

	return s_Instance;
}

void CChatFrameMgr::ReleaseInstance()
{
	if (s_Instance)
	{
		delete s_Instance;
		s_Instance = NULL;
	}
}

void CChatFrameMgr::Init()
{
	m_pLogic = CIMLogic::GetInstance();
}

void CChatFrameMgr::DestroyAllChatFrame()
{
	mapChatFrames::iterator it = m_mapChatFrames.begin();
	for (it = m_mapChatFrames.begin();it != m_mapChatFrames.end();++it)
	{
		CChatFrame *pChatFrame = it->second;
		delete pChatFrame;
		pChatFrame = NULL;
		
	}

	m_mapChatFrames.clear();

}

void CChatFrameMgr::OpenChatFrame(TCHAR *szTo)
{

	mapChatFrames::iterator it = m_mapChatFrames.find((CString)szTo);

	if (it != m_mapChatFrames.end())
	{
		it->second->BringWindowToTop();
	}else
	{
		CChatFrame *pChatFrame = new CChatFrame;
		_ASSERTE(pChatFrame);

		pChatFrame->Init(this,CAccountInfoMgr::GetInstance()->GetAccountName().GetBuffer(0),szTo);
		pChatFrame->Create(CChatFrame::IDD);
		pChatFrame->ShowWindow(SW_SHOW);

		m_mapChatFrames[szTo] = pChatFrame;
	}
}

void CChatFrameMgr::OnCloseChatFrame(TCHAR *szTo)
{

	mapChatFrames::iterator it = m_mapChatFrames.find((CString)szTo);

	if (it != m_mapChatFrames.end())
	{
		CChatFrame *pChatFrame = it->second;
		delete pChatFrame;
		m_mapChatFrames.erase(it);
	}
}

void CChatFrameMgr::AddOneMessage(TCHAR *szFrom,TCHAR *szMsg)
{
	mapChatFrames::iterator it = m_mapChatFrames.find((CString)szFrom);

	if (it != m_mapChatFrames.end())
	{
		it->second->AddOnMessage(szFrom,CAccountInfoMgr::GetInstance()->GetAccountName().GetBuffer(0),szMsg);
	}else
	{
		CChatFrame *pChatFrame = new CChatFrame;
		_ASSERTE(pChatFrame);

		pChatFrame->Init(this,CAccountInfoMgr::GetInstance()->GetAccountName().GetBuffer(0),szFrom);
		pChatFrame->Create(CChatFrame::IDD);
		pChatFrame->ShowWindow(SW_SHOW);
		pChatFrame->AddOnMessage(szFrom,CAccountInfoMgr::GetInstance()->GetAccountName().GetBuffer(0),szMsg);

		m_mapChatFrames[szFrom] = pChatFrame;
	}

}

void CChatFrameMgr::SendMsg(TCHAR *szTo,TCHAR *szMsg)
{
	if (m_pLogic)
	{
		m_pLogic->SendMsg(szTo,szMsg);
	}
}

